/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.entity.Favorite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import model.entity.Customer;
import model.entity.Orders;

/**
 *
 * @author lnngu_000
 */
public class CustomerJpaController implements Serializable {

    public CustomerJpaController( EntityManagerFactory emf) {
       
        this.emf = emf;
    }
    
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Customer customer) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (customer.getFavoriteCollection() == null) {
            customer.setFavoriteCollection(new ArrayList<Favorite>());
        }
        if (customer.getOrdersCollection() == null) {
            customer.setOrdersCollection(new ArrayList<Orders>());
        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Favorite> attachedFavoriteCollection = new ArrayList<Favorite>();
            for (Favorite favoriteCollectionFavoriteToAttach : customer.getFavoriteCollection()) {
                favoriteCollectionFavoriteToAttach = em.getReference(favoriteCollectionFavoriteToAttach.getClass(), favoriteCollectionFavoriteToAttach.getFavoriteId());
                attachedFavoriteCollection.add(favoriteCollectionFavoriteToAttach);
            }
            customer.setFavoriteCollection(attachedFavoriteCollection);
            Collection<Orders> attachedOrdersCollection = new ArrayList<Orders>();
            for (Orders ordersCollectionOrdersToAttach : customer.getOrdersCollection()) {
                ordersCollectionOrdersToAttach = em.getReference(ordersCollectionOrdersToAttach.getClass(), ordersCollectionOrdersToAttach.getOrderId());
                attachedOrdersCollection.add(ordersCollectionOrdersToAttach);
            }
            customer.setOrdersCollection(attachedOrdersCollection);
            em.persist(customer);
            for (Favorite favoriteCollectionFavorite : customer.getFavoriteCollection()) {
                Customer oldCustomerIdOfFavoriteCollectionFavorite = favoriteCollectionFavorite.getCustomerId();
                favoriteCollectionFavorite.setCustomerId(customer);
                favoriteCollectionFavorite = em.merge(favoriteCollectionFavorite);
                if (oldCustomerIdOfFavoriteCollectionFavorite != null) {
                    oldCustomerIdOfFavoriteCollectionFavorite.getFavoriteCollection().remove(favoriteCollectionFavorite);
                    oldCustomerIdOfFavoriteCollectionFavorite = em.merge(oldCustomerIdOfFavoriteCollectionFavorite);
                }
            }
            for (Orders ordersCollectionOrders : customer.getOrdersCollection()) {
                Customer oldCustomerIdOfOrdersCollectionOrders = ordersCollectionOrders.getCustomerId();
                ordersCollectionOrders.setCustomerId(customer);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
                if (oldCustomerIdOfOrdersCollectionOrders != null) {
                    oldCustomerIdOfOrdersCollectionOrders.getOrdersCollection().remove(ordersCollectionOrders);
                    oldCustomerIdOfOrdersCollectionOrders = em.merge(oldCustomerIdOfOrdersCollectionOrders);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findCustomer(customer.getCustomerId()) != null) {
                throw new PreexistingEntityException("Customer " + customer + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Customer customer) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            Customer persistentCustomer = em.find(Customer.class, customer.getCustomerId());
            Collection<Favorite> favoriteCollectionOld = persistentCustomer.getFavoriteCollection();
            Collection<Favorite> favoriteCollectionNew = customer.getFavoriteCollection();
            Collection<Orders> ordersCollectionOld = persistentCustomer.getOrdersCollection();
            Collection<Orders> ordersCollectionNew = customer.getOrdersCollection();
            Collection<Favorite> attachedFavoriteCollectionNew = new ArrayList<Favorite>();
            for (Favorite favoriteCollectionNewFavoriteToAttach : favoriteCollectionNew) {
                favoriteCollectionNewFavoriteToAttach = em.getReference(favoriteCollectionNewFavoriteToAttach.getClass(), favoriteCollectionNewFavoriteToAttach.getFavoriteId());
                attachedFavoriteCollectionNew.add(favoriteCollectionNewFavoriteToAttach);
            }
            favoriteCollectionNew = attachedFavoriteCollectionNew;
            customer.setFavoriteCollection(favoriteCollectionNew);
            Collection<Orders> attachedOrdersCollectionNew = new ArrayList<Orders>();
            for (Orders ordersCollectionNewOrdersToAttach : ordersCollectionNew) {
                ordersCollectionNewOrdersToAttach = em.getReference(ordersCollectionNewOrdersToAttach.getClass(), ordersCollectionNewOrdersToAttach.getOrderId());
                attachedOrdersCollectionNew.add(ordersCollectionNewOrdersToAttach);
            }
            ordersCollectionNew = attachedOrdersCollectionNew;
            customer.setOrdersCollection(ordersCollectionNew);
            customer = em.merge(customer);
            for (Favorite favoriteCollectionOldFavorite : favoriteCollectionOld) {
                if (!favoriteCollectionNew.contains(favoriteCollectionOldFavorite)) {
                    favoriteCollectionOldFavorite.setCustomerId(null);
                    favoriteCollectionOldFavorite = em.merge(favoriteCollectionOldFavorite);
                }
            }
            for (Favorite favoriteCollectionNewFavorite : favoriteCollectionNew) {
                if (!favoriteCollectionOld.contains(favoriteCollectionNewFavorite)) {
                    Customer oldCustomerIdOfFavoriteCollectionNewFavorite = favoriteCollectionNewFavorite.getCustomerId();
                    favoriteCollectionNewFavorite.setCustomerId(customer);
                    favoriteCollectionNewFavorite = em.merge(favoriteCollectionNewFavorite);
                    if (oldCustomerIdOfFavoriteCollectionNewFavorite != null && !oldCustomerIdOfFavoriteCollectionNewFavorite.equals(customer)) {
                        oldCustomerIdOfFavoriteCollectionNewFavorite.getFavoriteCollection().remove(favoriteCollectionNewFavorite);
                        oldCustomerIdOfFavoriteCollectionNewFavorite = em.merge(oldCustomerIdOfFavoriteCollectionNewFavorite);
                    }
                }
            }
            for (Orders ordersCollectionOldOrders : ordersCollectionOld) {
                if (!ordersCollectionNew.contains(ordersCollectionOldOrders)) {
                    ordersCollectionOldOrders.setCustomerId(null);
                    ordersCollectionOldOrders = em.merge(ordersCollectionOldOrders);
                }
            }
            for (Orders ordersCollectionNewOrders : ordersCollectionNew) {
                if (!ordersCollectionOld.contains(ordersCollectionNewOrders)) {
                    Customer oldCustomerIdOfOrdersCollectionNewOrders = ordersCollectionNewOrders.getCustomerId();
                    ordersCollectionNewOrders.setCustomerId(customer);
                    ordersCollectionNewOrders = em.merge(ordersCollectionNewOrders);
                    if (oldCustomerIdOfOrdersCollectionNewOrders != null && !oldCustomerIdOfOrdersCollectionNewOrders.equals(customer)) {
                        oldCustomerIdOfOrdersCollectionNewOrders.getOrdersCollection().remove(ordersCollectionNewOrders);
                        oldCustomerIdOfOrdersCollectionNewOrders = em.merge(oldCustomerIdOfOrdersCollectionNewOrders);
                    }
                }
            }
            
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = customer.getCustomerId();
                if (findCustomer(id) == null) {
                    throw new NonexistentEntityException("The customer with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            Customer customer;
            try {
                customer = em.getReference(Customer.class, id);
                customer.getCustomerId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The customer with id " + id + " no longer exists.", enfe);
            }
            Collection<Favorite> favoriteCollection = customer.getFavoriteCollection();
            for (Favorite favoriteCollectionFavorite : favoriteCollection) {
                favoriteCollectionFavorite.setCustomerId(null);
                favoriteCollectionFavorite = em.merge(favoriteCollectionFavorite);
            }
            Collection<Orders> ordersCollection = customer.getOrdersCollection();
            for (Orders ordersCollectionOrders : ordersCollection) {
                ordersCollectionOrders.setCustomerId(null);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
            }
            em.remove(customer);
            
        } catch (Exception ex) {
            try {
                
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Customer> findCustomerEntities() {
        return findCustomerEntities(true, -1, -1);
    }

    public List<Customer> findCustomerEntities(int maxResults, int firstResult) {
        return findCustomerEntities(false, maxResults, firstResult);
    }

    private List<Customer> findCustomerEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Customer.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Customer findCustomer(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Customer.class, id);
        } finally {
            em.close();
        }
    }

    public int getCustomerCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Customer> rt = cq.from(Customer.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
